<template>
  <div class="content-box" v-show="form.sourceId">
    <div class="subtitle">
      抽检规则
      <div v-hasPermi="['cq:rdcRule:edit']">
        <el-button size="mini" icon="el-icon-copy-document" @click="btnCopy">复制</el-button>
        <el-button size="mini" icon="el-icon-document-copy" :disabled="btnLoading" @click="btnPaste">粘贴</el-button>
        <el-button size="mini" type="primary" :disabled="listLoading" :loading="btnLoading" @click="btnSubmit">保存</el-button>
      </div>
    </div>
    <el-form ref="form" :model="form" :rules="rules" size="small" label-width="100px" @submit.native.prevent class="form" v-loading="listLoading">
      <el-tabs v-model="currProcessType" type="card" class="tab-box">
        <el-tab-pane v-for="item in processTypeList" :key="item" :label="dict.label.cq_process_type[item]" :name="item" />
      </el-tabs>
      <el-form-item prop="sourceId" class="hide" />
      <el-form-item prop="ruleId" class="hide" />
      <el-row>
        <el-col :sm="24" :lg="16">
          <el-form-item label="抽检规则" prop="ruleContent">
            <el-input v-model="form.ruleContent" type="textarea" :rows="3" placeholder="请输入抽检规则内容" :maxlength="3000" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :sm="8" :lg="6">
          <el-form-item prop="ruleType">
            <span slot="label">
              规则类型
              <el-tooltip placement="top">
                <div slot="content" style="white-space: pre-line">{{ showRuleRemark }}</div>
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <el-select v-model="form.ruleType" placeholder="请选择" default-first-option filterable style="width: 100%">
              <el-option-group v-for="group in ruleTypes" :key="group.label" :label="group.label">
                <el-option v-for="item in group.options" :key="item.value" :label="item.label" :value="+item.value" />
              </el-option-group>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :sm="8" :lg="4">
          <el-form-item label="量词单位" prop="ruleUnit"><el-input v-model.trim="form.ruleUnit" placeholder="请输入量词单位" :maxlength="50" /></el-form-item>
        </el-col>
        <el-col :sm="8" :lg="6">
          <el-form-item label="扣分对象" prop="deductObj">
            <el-select v-model="form.deductObj" placeholder="请选择" default-first-option filterable style="width: 100%">
              <el-option v-for="dict in dict.type.cq_deduct_obj" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :sm="8" :lg="4">
          <el-form-item label="扣分对象数量" prop="deductCount">
            <el-input-number v-model="form.deductCount" :min="1" :max="1e8" :precision="0" controls-position="right" />
          </el-form-item>
        </el-col>
      </el-row>
      <RdcRuleType ref="RdcRuleType" v-model="form.ruleJson" :rule-type="form.ruleType" />
    </el-form>
  </div>
</template>
<script>
// 编辑抽检规则
import { debounce, isObject } from '@/utils'
import { editFormMixin } from '@/utils/mixin'
import { listRdcRule, addRdcRule, updateRdcRule } from '@/api/qualityManage/cq'
import RdcRuleType from './RdcRuleType'
const levelTypes = ['1', '2', '3', '4', '9']
const deductTypes = ['5', '6', '7', '8', '10']
const copiedFields = ['ruleContent', 'ruleUnit', 'ruleType', 'ruleJson', 'deductObj', 'deductCount']
export default {
  components: { RdcRuleType },
  mixins: [editFormMixin],
  dicts: ['cq_process_type', 'cq_rule_type', 'cq_deduct_obj'],
  data() {
    return {
      form: {
        sourceId: '',
        processType: '',
        ruleId: '',
        ruleContent: '',
        ruleUnit: '处',
        ruleType: '',
        ruleJson: '',
        deductObj: 'all',
        deductCount: 1
      },
      rules: {
        ruleContent: [{ required: true, message: '请输入抽检规则内容' }],
        ruleUnit: [{ required: true, message: '请输入量词单位' }],
        ruleType: [{ required: true, message: '请选择抽检规则类型' }]
      },
      listLoading: false,
      ruleTypes: [],
      showRuleRemark: '',
      processTypeList: [],
      currProcessType: ''
    }
  },
  watch: {
    currProcessType(val) {
      val ? this.getRdcRule() : this.resetFields()
    },
    'form.ruleType'(val, oldVal) {
      // 初始赋值不处理
      if (val && !oldVal) return
      // 切换时初始化 ruleJson
      this.form.ruleJson = '[{}]'
    },
    'dict.type.cq_rule_type'(val) {
      if (!val?.length) return
      // 分组。前端固定，如后续出现其他，也需对应加抽检规则组件
      const level = []
      const score = []
      const other = []
      val.map(i => (levelTypes.includes(i.value) ? level.push(i) : deductTypes.includes(i.value) ? score.push(i) : other.push(i)))
      const group = [
        { label: '等级', options: level },
        { label: '扣分', options: score }
      ]
      if (other.length) group.push({ label: '其他', options: other })
      this.ruleTypes = group
      this.showRuleRemark = group.map(r => r.label + '\n' + r.options.map(i => `${i.label}: ${i.raw?.remark || ''}`).join('\n')).join('\n\n')
    }
  },
  created() {
    this.btnCopy = debounce(this.handleCopy, 500, true)
    this.btnPaste = debounce(this.handlePaste, 500, true)
  },
  methods: {
    resetFields() {
      this.$refs.form.resetFields()
      this.processTypeList = []
      this.currProcessType = ''
    },
    opened(item, { rdcCourses }) {
      const list = rdcCourses.split(',').filter(i => i)
      if (!list.length) return this.resetFields()
      this.processTypeList = list.sort()
      this.currProcessType = list[0]
      this.getRdcRule()
    },
    async getRdcRule() {
      const { form } = this
      this.listLoading = true
      const opt = { sourceId: form.sourceId, processType: this.currProcessType, delFlag: 0 }
      const res = await listRdcRule(opt).catch(() => false)
      this.listLoading = false
      if (res === false) return

      const data = res.data?.[0] || {}
      Object.keys(form)
        .filter(k => k !== 'sourceId')
        .map(k => (form[k] = typeof data[k] !== 'undefined' ? data[k] : this.formInitVals[k]))
      // 修复切换时因 ruleType 更改触发 ruleJson 值还原
      this.$nextTick(() => (form.ruleJson = data.ruleJson || ''))
    },
    async getRuleId() {
      const opt = { sourceId: this.form.sourceId, processType: this.currProcessType, delFlag: 0 }
      const res = await listRdcRule(opt).catch(() => false)
      if (res === false) return
      const ruleId = res.data?.[0]?.ruleId
      if (ruleId) this.form.ruleId = ruleId
    },
    async onSubmit() {
      const valid = await this.$refs.form.validate().catch(() => false)
      if (!valid) return
      const res1 = await this.$refs.RdcRuleType.validate().catch(() => false)
      if (!res1) return this.msgError('抽检规则配置有误')

      const opt = { ...this.form }
      !opt.processType && (opt.processType = this.currProcessType)

      this.btnLoading = true
      const submitApi = opt.ruleId ? updateRdcRule : addRdcRule
      const res = await submitApi(opt).catch(() => false)
      this.btnLoading = false
      if (res === false) return

      this.msgSuccess('保存成功')
      // if (!opt.ruleId) this.getRuleId()
      // 注: 始终再次调用获取列表
      this.getRuleId()
    },
    async handleCopy() {
      const valid = await this.$refs.form.validate().catch(() => false)
      const res1 = await this.$refs.RdcRuleType.validate().catch(() => false)
      if (!valid || !res1) return this.msgError('规则配置有误，请配置无误后再复制')

      const form = { ...this.form }
      const data = copiedFields.reduce((o, k) => !void (o[k] = form[k]) && o, {})
      localStorage.setItem('cqRdcRuleContent', JSON.stringify(data))
      this.msgSuccess('已复制')
    },
    async handlePaste() {
      const { form } = this
      let data = localStorage.getItem('cqRdcRuleContent')
      try {
        data = JSON.parse(data)
      } catch (err) {
        return this.msgInfo('内容解析失败')
      }
      if (!data) return this.msgInfo('暂无内容，不能粘贴')
      if (!isObject(data)) return this.msgInfo('内容格式错误，不能粘贴')

      const res1 = await this.$confirm('粘贴会覆盖现有配置，确定继续?', '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      copiedFields.map(k => (form[k] = data[k] || this.formInitVals[k]))
      this.$nextTick(() => (form.ruleJson = data.ruleJson || ''))
      this.msgSuccess('粘贴成功')
    }
  }
}
</script>
<style lang="scss" scoped>
.content-box {
  min-width: 500px;
  overflow-x: auto;
  padding-top: 15px;
}
.subtitle {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #f8f8f9;
  color: #515a6e;
  font-size: 12px;
  font-weight: 700;
  padding: 10px;
}
.tab-box {
  zoom: 0.9;
  /deep/ .el-tabs__item {
    font-size: 12px;
  }
}
.form {
  height: 385px;
  overflow-y: auto;
  padding-top: 20px;
  // 解决 loading 时没覆盖提示信息
  padding-bottom: 1px;
}
</style>
